package com.atguigu.flink.chapter11.window;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import java.time.Duration;

import static org.apache.flink.table.api.Expressions.$;

/**
 * @Author lzc
 * @Date 2022/11/1 08:48
 */
public class Flink_04_Window_Over_1 {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        SingleOutputStreamOperator<WaterSensor> stream = env
            .fromElements(
                new WaterSensor("s1", 1000L, 10),
                new WaterSensor("s1", 1000L, 10),
                new WaterSensor("s1", 2000L, 20),
                new WaterSensor("s1", 3000L, 30),
                new WaterSensor("s1", 4000L, 40),
                new WaterSensor("s1", 5000L, 50)
            )
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((ws, ts) -> ws.getTs())
            );
    
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        Table table = tEnv.fromDataStream(stream, $("id"), $("ts").rowtime(), $("vc"));
        tEnv.createTemporaryView("sensor", table);
        
        // 2. 在 sql 中使用使用 over 窗口
    
        tEnv.sqlQuery("select " +
                          " id, ts, vc, " +
//                          " sum(vc) over(partition by id order by ts rows between unbounded preceding and current row)" +
//                          " sum(vc) over(partition by id order by ts rows between 1 preceding and current row)" +
                            // sql中 range 时候也应该写current row
//                          " sum(vc) over(partition by id order by ts range between unbounded preceding and current row)" +
//                          " sum(vc) over(partition by id order by ts range between interval '2' second preceding and current row)" +
                          " sum(vc) over(partition by id order by ts)" +
                          "from sensor")
            .execute()
            .print();
    }
}
